package com.zecan.binarysearch;

/**
 * \* Created with IntelliJ IDEA.
 * \* User: lenovo
 * \* Date: 2021/10/10
 * \* Time: 11:30
 * \* Description:
 * \
 */
public class BinarySearch {
    public static void main(String[] args) {
        int[] arr = new int[] {1,5,87,88,99,123,776};
        int i = binarySearch(arr, 5);
        System.out.println("i  = " + i);
    }

    public static int binarySearch(int[] arr, int target) {
        int left = 0;
        int right = arr.length - 1;

        while(left <= right) {
            int mid = (left + right / 2);
            if(arr[mid] == target) return mid; // 如果下标的值就是要查找的值 则直接返回
            else if (arr[mid] > target) right = mid - 1;  // 如果当前下标的值大于要查找的值 则缩小到左边范围
            else left = mid + 1; // 如果当前下标的小于要查找的值  则缩小到右边的范围
        }
        return -1; //如果找不到则直接返回 -1
    }
}
